package com.wmlive.hhvideo.heihei.bells.presenter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.base.BasePresenter;
import com.wmlive.hhvideo.heihei.beans.bell.BellContent;
import com.wmlive.hhvideo.heihei.beans.bell.BellJump;
import com.wmlive.hhvideo.heihei.beans.bell.BellMessage;
import com.wmlive.hhvideo.heihei.beans.main.Author;
import com.wmlive.hhvideo.heihei.bells.view.BellsView;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageDefaultTable;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageUserTable;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.utils.CollectionUtil;
import com.wmlive.hhvideo.utils.KLog;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 读取消息
 * Created by vhawk on 2017/7/5.
 */
public class BellsPresenter extends BasePresenter<BellsView> {

    private static final int PAGE_SIZE = 20;

    private List<IMMessageDefaultTable> imDefaultEntryList;

    public BellsPresenter(BellsView view) {
        super(view);
    }


    /**
     * 读取消息
     *
     * @param listid
     */
    public void readBellMessage(final String createTime, final long listid) {

        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, List<BellMessage>>() {
                    @Override
                    public List<BellMessage> apply(@NonNull Integer integer) throws Exception {
                        List<BellMessage> bellMessageList = new ArrayList<>();
                        if (AccountUtil.isLogin()) {// 登录状态，按照user 读取数据库
                            readUserBellMessage(createTime, listid, bellMessageList);

                        } else {// 未登录状态，读取默认数据库
                            readDefaultBellMessage(createTime, listid, bellMessageList);
                        }
                        return bellMessageList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<BellMessage>>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull List<BellMessage> bellMessageList) {
                if (viewCallback != null) {
                    boolean hasMore = !(CollectionUtil.isEmpty(bellMessageList) || bellMessageList.size() < PAGE_SIZE);
                    viewCallback.addBellMessage(hasMore, bellMessageList, listid == 0);
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

        updateAllMessageReadStatus();
    }

    /**
     * 读取默认数据库消息
     *
     * @param createTime
     * @param listid
     * @param bellMessageList
     */
    private synchronized void readDefaultBellMessage(String createTime, long listid, List<BellMessage> bellMessageList) {
        IMMessageDefaultDBManager defaultDBManager = IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp());
        List<IMMessageDefaultTable> imDefaultEntryList = null;
        if (listid > 0) {
            imDefaultEntryList = defaultDBManager.getImDefaultEntryListByCreateTimeDesc(listid, createTime, PAGE_SIZE);
        } else {
            imDefaultEntryList = defaultDBManager.getImDefaultEntryListDesc(PAGE_SIZE);
        }

        if (!CollectionUtil.isEmpty(imDefaultEntryList)) {
            for (IMMessageDefaultTable defaultTable : imDefaultEntryList) {
                Author fromUser = JSON.parseObject(defaultTable.getFrom_user(), Author.class);
                Author toUser = JSON.parseObject(defaultTable.getTo_user(), Author.class);
                BellContent bellContent = null;
                if (!TextUtils.isEmpty(defaultTable.getContent())) {
                    bellContent = JSON.parseObject(defaultTable.getContent(), BellContent.class);
                }
                BellMessage bellMessage = new BellMessage();
                bellMessage.setMsg_type(defaultTable.getMsg_type())
                        .setListid(defaultTable.getListid())
                        .setMsg_id(defaultTable.getMsg_id())
                        .setTips(defaultTable.getTips())
                        .setFrom_user(fromUser)
                        .setTo_user(toUser)
                        .setContent(bellContent);

                if (TextUtils.isDigitsOnly(defaultTable.getCreate_time())) {
                    bellMessage.setCreate_time(Long.parseLong(defaultTable.getCreate_time()));
                }
                bellMessageList.add(bellMessage);
            }
        }
    }

    /**
     * 读取登录用户推送消息
     *
     * @param createTime
     * @param listid
     * @param bellMessageList
     */
    private synchronized void readUserBellMessage(String createTime, long listid, List<BellMessage> bellMessageList) {
        IMMessageUserDBManager userDBManager = IMMessageUserDBManager.getInstance(DCApplication.getDCApp());
        List<IMMessageUserTable> imUserEntryList = null;

        if (listid > 0) {
            imUserEntryList = userDBManager.getImUserEntryListByCreateTimeDesc(listid, createTime, PAGE_SIZE);
        } else {
            imUserEntryList = userDBManager.getImUserEntryListDesc(PAGE_SIZE);
        }

        if (!CollectionUtil.isEmpty(imUserEntryList)) {

            for (IMMessageUserTable userTable : imUserEntryList) {

                Author fromUser = JSON.parseObject(userTable.getFrom_user(), Author.class);
                Author toUser = JSON.parseObject(userTable.getTo_user(), Author.class);
                BellContent bellContent = null;
                if (!TextUtils.isEmpty(userTable.getContent())) {
                    bellContent = JSON.parseObject(userTable.getContent(), BellContent.class);
                }

                BellMessage bellMessage = new BellMessage();
                bellMessage.setMsg_type(userTable.getMsg_type())
                        .setListid(userTable.getListid())
                        .setMsg_id(userTable.getMsg_id())
                        .setTips(userTable.getTips())
                        .setFrom_user(fromUser)
                        .setTo_user(toUser)
                        .setContent(bellContent);

                if (TextUtils.isDigitsOnly(userTable.getCreate_time())) {
                    bellMessage.setCreate_time(Long.parseLong(userTable.getCreate_time()));
                }

                KLog.v("vhawk", "time = " + userTable.getCreate_time());
                bellMessageList.add(bellMessage);
            }
        }
    }

    /**
     * 将所有消息设为已读状态
     */
    private void updateAllMessageReadStatus() {
        if (AccountUtil.isLogin()) {
            IMMessageUserDBManager userDBManager = IMMessageUserDBManager.getInstance(DCApplication.getDCApp());
            userDBManager.updateImDefaultEntryRead();
        } else {
            IMMessageDefaultDBManager defaultDBManager = IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp());
            defaultDBManager.updateImDefaultEntryRead();
        }
    }

    private void addMockSystemMessage(List<BellMessage> bellMessageList) {

//        "message": {
//            "msg_type": "system",
//                    "from_user": {
//                "name": "senga",
//                        "cover_url": "",
//                        "honours": [],
//                "dc_num": "",
//                        "id": 10017,
//                        "description": ""
//            },
//            "content": {
//                "title": ""
//                "desc": "活动或通知内容",
//                        "jump": {
//                    "text": "查看",
//                            "link": "hhvideo://opus/detail?id=10001"
//                }
//            },
//            "msg_id": 1234567890123456,
//                    "create_time": 1348831860,
//                    "tips": "【评论消息】不支持的消息类型，请升级最新客户端。"
//        }

        Author fromUser = new Author();
        fromUser.setName("senga");

        BellJump bellJump = new BellJump();
        bellJump.setText("查看")
                .setLink("hhvideo://opus/detail?id=10001");

        BellContent bellContent = new BellContent();
        bellContent.setTitle("")
                .setDesc("活动或通知内容")
                .setJump(bellJump);

        BellMessage bellMessage = new BellMessage();
        bellMessage.setMsg_type("system")
                .setMsg_id(234567 + "")
//                .setTips(defaultTable.getTips())
                .setFrom_user(fromUser)
//                .setTo_user(toUser)
                .setContent(bellContent);

        bellMessageList.add(bellMessage);

//
//        BellMessage bellMessage = new BellMessage();
//        bellMessage.setMsg_type(defaultTable.getMsg_type())
//                .setListid(defaultTable.getListid())
//                .setMsg_id(defaultTable.getMsg_id())
//                .setTips(defaultTable.getTips())
//                .setFrom_user(fromUser)
//                .setTo_user(toUser)
//                .setContent(bellContent);
//
//        bellMessageList.add(bellMessage);
    }
}
